#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> 
#include <sys/stat.h>  
#include <termios.h>
#include <unistd.h>
#include <iostream>
#include <time.h>

using namespace std;

int number(unsigned char* str,int buflength)
{
    int num = 0;
    for(int i = 0;i<buflength;i++)
    {
        if(int(str[i]) == 0)  return num;
        num++;
    }
    return num;
}

int main()
{
    unsigned char buf[800];
    int fd;
    int statu;
    int len;
    int flag = 1;
    char* port = "/dev/ttyACM0";
    cout<<"输入数字1表示发送数据,输入数字2表示读入数据"<<endl;
    cin>>statu;
    if(statu == 1)
    {
       if(fd <0)
       {
           cout<<"port open error!"<<endl;
       }
       while(1)
       {
            fd = open(port, O_RDWR);
            if(fd > 0) break;
       }
       cout<<"port open success!"<<endl;
        while(1)
        {
            memset(buf,0,sizeof(buf));
            cin>>buf;
            len = write(fd,buf,number(buf,800));
        }
    }
    if(statu == 2)
    {
        if(fd <0)
       {
           cout<<"port open error!"<<endl;
       }
        while(1)
        {
            fd = open(port, O_RDWR|O_NOCTTY|O_DSYNC);
            if(fd > 0) break;
        }
       while(1)
       {
           memset(buf,0,sizeof(buf));
           len = read(fd,buf,sizeof(buf)-1);
           if(len >0)
           {
               cout<<"read data!"<<endl;
               cout<<buf<<endl;
               flag = 1;
               tcflush(fd, TCIOFLUSH);
           }
           else
           {
               if(flag == 1)
               {
                   cout<<"read no data!"<<endl;
                   flag = 0;
               }
           }
           
       }
    }
    return 0;
}

